import Foundation

// let pattern = "[a-zA-Z]+@[a-zA-Z]+\\.[a-zA-Z]{2,}"
// do {
//     let regex = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
// } catch {
//     print("正则表达式错误：\(error)")
// }

let text = "Contact us at support@example.com or sales@company.org"
let pattern = "[a-zA-Z]+@[a-zA-Z]+\\.[a-zA-Z]{2,}"
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.matches(
    in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
for match in matches {
    let matchRange = match.range
    let matcheString = (text as NSString).substring(with: matchRange)
    print("匹配到的邮箱地址：\(matcheString)")
}

// 提取捕获重复组
let text1 = "My email is alice@example.com"
let pattern1 = "([a-zA-Z]+)@([a-zA-Z]+)\\.([a-zA-Z]{2,})"
let regex1 = try! NSRegularExpression(pattern: pattern1, options: [.caseInsensitive])

if let match = regex1.firstMatch(
    in: text1, options: [], range: NSRange(location: 0, length: text1.utf16.count))
{
    let username = (text1 as NSString).substring(with: match.range(at: 1))
    let domain = (text1 as NSString).substring(with: match.range(at: 2))
    let tld = (text1 as NSString).substring(with: match.range(at: 3))
    print("Username: \(username), Domain: \(domain), TLD: \(tld)")
}

// 替换匹配
let text2 = "Contact: support@example.com"
let pattern2 = "[a-zA-Z]+@[a-zA-Z]+\\.[a-zA-Z]{2,}"
let regex2 = try! NSRegularExpression(pattern: pattern2)
let result = regex2.stringByReplacingMatches(
    in: text2, options: [], range: NSRange(location: 0, length: text2.utf16.count),
    withTemplate: "[REDACTED]")
print(result)  // 输出: Contact: [REDACTED]

// 验证字符串
// 检查字符串是否完全匹配正则表达式。
let email = "test@example.com"
let pattern3 = "^[a-zA-Z]+@[a-zA-Z]+\\.[a-zA-Z]{2,}$"
let regex3 = try! NSRegularExpression(pattern: pattern3, options: [.caseInsensitive])
let isValid =
    regex3.firstMatch(
        in: email, options: [], range: NSRange(location: 0, length: email.utf16.count)) != nil
print("Is valid email: \(isValid)")  // 输出: Is valid email: true
